package com.arpa.wms.controller;

import cn.hutool.core.collection.CollUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.dto.DamagedDTO;
import com.arpa.wms.domain.dto.DamagedExcelDTO;
import com.arpa.wms.domain.entity.Damaged;
import com.arpa.wms.domain.vo.DamagedVO;
import com.arpa.wms.service.IDamagedService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 破损单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-20
 */
@Api(tags = "破损单")
@RestController
@RequestMapping(value="/damaged", produces = "application/json;charset=UTF-8")
@Log4j2
public class DamagedController {

   @Autowired
   private IDamagedService iDamagedService;

    /**
     * 获取 破损单 列表
     *
     * @param damagedDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 破损单 列表", notes = "获取 破损单 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DamagedVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(DamagedDTO damagedDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录账号授权的仓库过滤
            damagedDTO.setWarehouseCodes(authMap.get(CommonConst.WAREHOUSE_CODES));
            //登录账号授权的货主过滤
            damagedDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            damagedDTO.setGroupCode(UserUtil.getBranchCode());
            DamagedVO damagedVoSum = iDamagedService.queryListSum(damagedDTO);
            List<DamagedVO> damagedVOList = iDamagedService.queryList(damagedDTO);

            Page returnPage = new Page(damagedDTO.getPageNum(),damagedDTO.getPageSize());
            returnPage.setRecords(damagedVOList);
            returnPage.setTotal(damagedVoSum.getTotal());
            returnPage.setSumObject(damagedVoSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 破损单
     *
     * @param entity Damaged
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 破损单 ", notes = "添加 破损单 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody @Validated(Damaged.Save.class) Damaged entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            iDamagedService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取破损单详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取破损单详情", notes = "获取破损单详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "破损单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Damaged.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result damaged(@PathVariable String code, HttpServletRequest request) {
        try {
            DamagedVO damagedVO = iDamagedService.getVoByCode(code);
            return Result.ok().data(damagedVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改破损单
     *
     * @param entity 破损单
     * @param request
     * @return
     */
    @ApiOperation(value = "修改破损单", notes = "修改破损单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(Damaged.Update.class) Damaged entity, HttpServletRequest request) {
        int updateNum = iDamagedService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 破损单
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 破损单 ", notes = "删除 破损单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iDamagedService.batchdel(codes);

            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 作废破损单
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "作废破损单 ", notes = "作废破损单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @PutMapping("/blank")
    public Result blank(@RequestParam String code, HttpServletRequest request) {
        try {
            Result result=iDamagedService.blank(code);

            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 审核
     *
     * @param danaged
     * @param request
     * @return
     */
    @ApiOperation(value = "审核", notes = "审核", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/audit")
    public Result audit(@RequestBody @Validated(Damaged.Audit.class)Damaged danaged, HttpServletRequest request) {
        try {
            Result result=iDamagedService.audit(danaged);

            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "报损 导入 预览", notes = "报损 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/damagedView")
    public Result initializationView(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<DamagedExcelDTO> list = EasyExcelUtil.read(url.openStream(), DamagedExcelDTO.class,2);
            if(CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<DamagedExcelDTO> damagedExcelDTOList = iDamagedService.damagedView(list);
            return new Result().data(damagedExcelDTOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    @ApiOperation(value = "报损 导入", notes = "报损 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/damagedImport")
    public Result initializationImport(HttpServletRequest request) {
        try {
            iDamagedService.damagedImport();
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
 }
